import React, { useState, useEffect } from 'react';
import logo from './logo.svg';
import styles from './App.module.css';
import robots from './mockdata/robots.json'
import Robot from './compontents/Robot';
import RobotDiscount from './compontents/RobotDiscount';
import ShoppingCart from './compontents/ShoppingCart'
interface Props {
}
interface State {
  robotGallery: any[];
  count: number;
}

const App: React.FC<Props> = (props: Props) => {
  const [count, setCount] = useState<number>(0)
  const [robotGallery, setRobotGallery] = useState<any>([])
  const [loading, setLoading] = useState<boolean>(false)
  const [error, setError] = useState<string>()

  useEffect(() => {
    // console.log('useEffect')
    document.title = `点击${count}次`
  }, [count])

  useEffect(() => {
    // fetch('https://jsonplaceholder.typicode.com/users')
    // .then(response => response.json())
    // .then(data => setRobotGallery(data))

    const fetchData = async () => {
      setLoading(true)
      try {
        const response = await fetch(`https://jsonplaceholder.typicode.com/users/`)
        const data = await response.json()
        setRobotGallery(data)
      } catch (e: any) {
        console.log(e)
        setError(e.message)
      }

      setLoading(false)
    }
    fetchData()
  }, [])
  // constructor(props: Props) {
  //   super(props);
  //   this.state = {
  //     robotGallery:[],
  //     count: 0
  //   }
  // }
  // 生命周期第二阶段：更新
  // componentDidMount(){
  //   fetch('https://jsonplaceholder.typicode.com/users')
  //   .then(response => response.json())
  //   .then((data) => {
  //     this.setState({robotGallery:data})
  //   })
  // }
  // render() {
  return (
    <div className={styles.app}>
      <div className={styles.appHeader}>
        <img src={logo} className={styles.appLogo} />
        <h1>机器人</h1>
      </div>
      <button
        onClick={() => {
          setCount(count + 1);
          // this.setState((preState, preProps)=>{
          //   return {count: preState.count + 1}
          // })  
          // this.setState((preState, preProps)=>{
          //   return {count: preState.count + 1}
          // }) 
          // this.setState((preState, preProps)=>{
          //   return {count: preState.count + 1}
          // }) 
        }}
      >Click</button>
      <div>{count}</div>
      <ShoppingCart />
      {
        !error || error !== '' && <div>网站出错：{error}</div>
      }
      {
        loading ? <h1>loading 加载中...</h1> :
          <div className={styles.robotList}>
            {robotGallery.map((r: any, index: number) => {
              return (
                index % 2 === 0 ?
                  <RobotDiscount id={r.id} name={r.name} email={r.email} key={'robot'+index} />
                  :
                  <Robot id={r.id} name={r.name} email={r.email} key={'robot'+index} />
              )
            })}
          </div>
      }

    </div>
  );
  // }
}

export default App;
